import java.util.Stack;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {
    }
    TreeNode(int val) {
        this.val = val;
    }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class testwork1 {


    public String tree2str(TreeNode root) {
        StringBuilder str = new StringBuilder();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {

            while (root != null || !stack.isEmpty()) {

                str.append(root.val);
                if (root.left != null) {
                    str.append("(");
                    str.append("root.left.val");
                    stack.push(root.left);
                } else {
                    if (root.right != null) {
                        str.append("()");
                    } else {
                        return"";
                    }
                }
                if (root.right != null) {
                    str.append("root.right.val");
                    str.append(")");
                    stack.push(root.right);
                } else {
                    return"";
                }
                stack.pop();
            }
        }
        String st= String.valueOf(str);
        return st;
    }
}
